var servicePlanTable = function() {
	var validator;
	return {
		init : function() {
			var tableId = "servicePlan_table";
			util.initCheckBox(tableId);
			var checkBoxDivStr = '<div class="checker" onclick="util.selectCheckBox(\'' + tableId + '\', this)"><span><input type="checkbox" class="checkboxes"></span></div>';

			function queryData(sSource, aoData, fnCallback) {
				aoData.push({
					"name" : "customer",
					"value" : $("#id_cusName").val().trim()
				});
				aoData.push({
					"name" : "planType",
					"value" : $("#id_planType").val()
				});
				aoData.push({
					"name" : "planStatus",
					"value" : $("#id_planStatus").val()
				});
				$.ajax({
					"type" : "post",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						fnCallback(resp);
					}
				});
			};

			$('#servicePlan_table').DataTable({
				"processing" : true,
				"serverSide" : true,
				"sAjaxSource" : "main/servicePlan/getServicePlan.mvc",
				"fnServerData" : queryData,
				"pageLength" : 10,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"oLanguage" : util.getDToLanguage(),
				"columns" : [ {
					"data" : "pkId",
					"render" : function(data, type, full, meta) {
						 return '<div class="checker" onclick="util.selectCheckBox(\'' + tableId + '\', this)"><span><input type="checkbox" class="checkboxes"/></span></div>';
					},
					"bSortable" : false
				},
				{
					"data" : "planCode",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "planStatus",
					"bSortable" : false,
					"render" : function(data, type, full, meta) { 
						if("1"==data){
							return "未处理";
						} else if("2"==data){
							return "已确认";
						} else if("3"==data) {
							return "处理中";
						} else if("4"==data) {
							return "已解决";
						} else if("5"==data) {
							return "已关闭";
						} else {
							return null;
						}
					},
					"defaultContent": ""
				},
				{
					"data" : "planType",
					"bSortable" : false,
					"render" : function(data, type, full, meta) { 
						if("1"==data){
							return "巡检计划";
						} else if("2"==data){
							return "维保计划";
						} else if("3"==data) {
							return "培训计划";
						} else {
							return null;
						}
					},
					"defaultContent": ""
				},
				{
					"data" : "planImportance",
					"bSortable" : false,
					"render" : function(data, type, full, meta) { 
						if("1"==data){
							return "一般";
						} else if("2"==data){
							return "中等";
						} else if("3"==data) {
							return "紧急";
						} else {
							return null;
						}
					},
					"defaultContent": ""
				},
				{
					"data" : "submitterName",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "cusName",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "planContent",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "planStartDateStr",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "planEndDateStr",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"bSortable" : false,
					"render" : function(data, type, full, meta) {
						 return "<a  data-pkid='"+full.pkId+"' class=\"showDetail\" style=\"cursor:pointer;color:blue;\" >查看</a>";
					}
				}
				],
				"fnDrawCallback" : function(oSetting) {
					util.clearSelected(tableId);
				}
			});

			//新增
			$("#plan_table_add").on('click', function(e) {
				$("#plan_add_title").text("新增计划");
				util.getDictByParentKey(null, 'customer', '请选择','main/servicePlan/findCustomerOpt.mvc');
				$.ajax({
					"type" : "post",
					"url" : "main/servicePlan/getUserNamebyLoginName.mvc",
					"dataType" : "json",
					"async":false,
					"success" : function(resp) {
						$("#submitter").val(resp.username);
						$("#submitter_id").val(resp.userId);
					}
				});
				$("#add-plan").modal({show:true,keyboard:false});
			});

			//编辑
			$("#plan_table_edit").on('click', function(e) {
				var d = [];
				d = util.getCheckedData("servicePlan_table");
				if (d.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行操作！");
					return false;
				}else if(d[0].planStatus!= '1') {
					util.showModal("#_alertModal", "服务计划已确认，无法编辑！");
					return false;
				}

				$("#plan_add_title").text("编辑计划");
				util.getDictByParentKey(null, 'customer', '请选择','main/servicePlan/findCustomerOpt.mvc');
				var _plan = [];
				_plan = getPlanById(util.getCheckedData("servicePlan_table")[0].pkId);
				$("#pkId").val(_plan.pkId);
				$("#planCode").val(_plan.planCode);
				$("#planType").val(_plan.planType);
				$("#planImportance").val(_plan.planImportance);
				$("#submitter_id").val(_plan.submitter);
				$("#submitter").val(_plan.submitterName);
				$("#customer").val(_plan.customer);
				$("#planContent").val(_plan.planContent);
				$("#planDescription").val(_plan.planDescription);
				$("#planStartDate").val(_plan.planStartDateStr);
				$("#planEndDate").val(_plan.planEndDateStr);
				$("#contacts").val(_plan.contacts);
				$("#contactNumber").val(_plan.contactNumber);

				$("#add-plan").modal({show:true,keyboard:false});
			});

			//查看
			$("#servicePlan_table").on('click', 'a.showDetail', function(e) {
				var pkId = $(this).attr("data-pkId");
				var _plan = [];
				_plan = getPlanById(pkId);
				$("#detail_planCode").text(_plan.planCode);
				if("1" == _plan.planImportance){
					$("#detail_planImportance").text("一般");
				}else if("2" == _plan.planImportance){
					$("#detail_planImportance").text("中等");
				}else if("3" == _plan.planImportance){
					$("#detail_planImportance").text("紧急");
				}
				if("1"==_plan.planType){
					$("#detail_planType").text("巡检计划");
				} else if("2"==_plan.planType){
					$("#detail_planType").text("维保计划");
				} else if("3"==_plan.planType) {
					$("#detail_planType").text("培训计划");
				} 
				//$("#detail_planType").text(_plan.planType);
				//$("#detail_planImportance").text(_plan.planImportance);
				$("#detail_submitter").text(_plan.submitterName);
				$("#detail_customer").text(_plan.cusName);
				$("#detail_planContent").text(_plan.planContent);
				$("#detail_planDescription").val(_plan.planDescription);
				$("#detail_planStartDate").text(_plan.planStartDateStr);
				$("#detail_planEndDate").text(_plan.planEndDateStr);
				$("#detail_contacts").text(_plan.contacts);
				$("#detail_contactNumber").text(_plan.contactNumber);

				$("#plan-detail").modal({show:true,keyboard:false});
			});

			$("#plan-detail").on('click', '.close', function(e) {
				e.preventDefault();
				$("#plan-detail .my-text").text("");
				$("#detail_planDescription").val("");
			});

			//删除 -----begin
			$("#plan_table_del").on('click', function(){
				debugger
				var d = [];
				d = util.getCheckedData("servicePlan_table");
				if (d.length == 0) {
					util.showModal("#_alertModal", "请选择要操作的记录！");
				} else if(d.length > 0 ) {
					var flag = true;
					for (var i = 0; i < d.length; i++) {
						if(d[i].planStatus !="1"){
							flag = false;
							break;
						}
					}
					if(!flag){
						util.showModal("#_alertModal", "某些服务计划已确认，无法删除！");
						return false;
					}
				}
				util.showModal("#_confirmModal", "您确定要删除选中的记录？", "_confirmModal_yes");
				
			});
			
			$("#_confirmModal").on('click', '#_confirmModal_yes', function() {
				var d = [];
				d = util.getCheckedData("servicePlan_table");
				var idArray=[];
				for (var i=0;i<d.length;i++) {
					idArray.push(d[i].pkId);
				}
				var table = $('#servicePlan_table').DataTable();
				var currentPage =table.page();
				$.ajax({
					"type" : "post",
					"url" : "main/servicePlan/deleteServicePlan.mvc",
					"dataType" : "json",
					"async":false,
					"data" : {
						"pkId" : idArray.join(",")
					},
					"success" : function(resp) {
						if(resp.msg=='SUCCESS'){
							rmsBox.notify('success', {msg: '删除成功！'});
							table.page(currentPage).draw('page');
						}else {
							rmsBox.notify('error', {msg: '删除失败！',delay:3000});
						}
					}
				});
			});
			//删除 -----end



			$("#form_btn_save").on('click', function(e) {
				e.preventDefault();
				debugger
				validator = validateMyForm("plan_form");
				if(validator.form()){
					save();
				}else{
					return false;
				}
			});

			// 查询
			$("#btn_query").click(function(e) {
				debugger
				var table = $('#servicePlan_table').DataTable();
				table.draw(true);
			});
			// 重置
			$("#btn_reset").click(function() {
				$("#customer_search_form")[0].reset();
				$(".select2-selection__rendered").empty();
				$(".select2-selection__rendered").append("<span class='select2-selection__placeholder'>请选择</span>");
			});
			function getPlanById(pkId) {
				var data = [];
				$.ajax({
					"type" : "post",
					"url" : "main/servicePlan/getPlanById.mvc",
					"dataType" : "json",
					"async":false,
					"data" : {
						"pkId" : pkId
					},
					"success" : function(resp) {
						data = resp;
					}
				});
				return data;
			}

			/*
			 * validate 自定义验证
			 */
			function validateMyForm(formId){
				return $( '#' + formId ).validate({  
					errorElement: 'em',
					errorClass: 'redStar',
					focusInvalid: false, 
					ignore: "",
			        rules:{  
			        	planCode:{
			        		required:true,
			        		checkRepeatPlanCode:true,
			        		checkFormat:true
			        	},
			        	planType:'required',
			        	planImportance:'required',
			        	submitter:'required',
			        	contactNumber: {checkTelNumber:true}
			            },  
			        messages:{  
			        	planCode:{
			        		required:'不能为空',
			        		checkRepeatPlanCode:'编码重复',
			        		checkFormat:'只能输入英文和数字'
			        	},
			        	planType:'不能为空',
			        	planImportance:'不能为空',
			        	submitter:'不能为空',
			        	contactNumber : '请输入正确的手机号'
			            }, 
			            errorPlacement: function (error, element) { 
			            	//默认以span形式显示在输入框后
		                   error.insertAfter(element);
		                   $(element.next()).attr('title', $(error).text()).tooltip();
		                   $(error).text('');
		                }
			    });
			};

			//校验手机号码
			$.validator.addMethod("checkTelNumber",function(value,element,params){
				var contactNumber = $("#contactNumber").val();
				var flag = true;
				var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;
				if(contactNumber&&contactNumber!=""){
					if (!myreg.test(contactNumber)) {  
	            		flag = false;  
		            } 
				}
	            return flag;
			},"");

			$.validator.addMethod("checkFormat",function(value,element,params){
				var planCode = $("#planCode").val();
				var reg = /^[A-Za-z0-9]+$/;
				return reg.test(planCode);
			},"");
			//校验编码是否重复
			$.validator.addMethod("checkRepeatPlanCode",function(value,element,params){
				var planCode = $("#planCode").val();
				var pkId = $("#pkId").val();
				var flag = true;
				$.ajax({
					"type" : "post",
					"url" : "main/servicePlan/checkRepeatPlanCode.mvc",
					"dataType" : "json",
					"async":false,
					"data" : {
						'planCode':planCode,
						'pkId':pkId
					},
					"success" : function(resp) {
						if(resp.msg == false) {
							flag = false;
						}
					}
				});
				return flag;
			},"");

			function save(){
				var table = $('#servicePlan_table').DataTable();
				var currentPage =table.page();
				var d = {};
				d['pkId'] = $("#pkId").val();
				d['planCode'] = $("#planCode").val();
				d['planType'] = $("#planType").val();
				d['planImportance'] = $("#planImportance").val();
				d['submitter'] =  $("#submitter_id").val();
				d['submitterName'] = $("#submitter").val();
				d['customer'] = $("#customer").val();
				d['planContent'] = $("#planContent").val();
				d['planDescription'] = $("#planDescription").val();
				d['planStartDateStr'] = $("#planStartDate").val();
				d['planEndDateStr'] = $("#planEndDate").val();
				d['contacts'] = $("#contacts").val();
				d['contactNumber'] = $("#contactNumber").val();
				$.ajax({
					"type" : "post",
					"url" : "main/servicePlan/saveOrUpdateServicePlan.mvc",
					"dataType" : "json",
					"async":false,
					"data" : d,
					"success" : function(resp) {
						debugger
						if(resp.msg=='SUCCESS'){
							rmsBox.notify('success', {msg: '保存成功！'});
							$("#form_btn_close").click();
							table.page(currentPage).draw('page');
						}else{
							rmsBox.notify('error', {msg: '保存失败！',delay:3000});
						}
						
					}
				});
			};

			//关闭弹窗清空表单内容
			$("#form_btn_close").on("click", function(){
				$("#plan_form")[0].reset();
				$("#pkId").val("");
				$("#submitter_id").val("");
				if (validator) {
					validator.resetForm();
				}
			});


			
			$(function(){
				
				util.initCustomerSelect("id_cusName","220px");
				$('.search-body input').bind('keyup', function(event) {
					if (event.keyCode == "13") {
						//回车执行查询
						$('.search-button #btn_query').click();
					}
				});
	
			});


			
		}
	};
}();